# Program to generate 500 random reshuffles of informal competition (infc)

# install.packages("dplyr")
# install.packages("haven")

library(haven)   # for write_dta
library(dplyr)

# Set the working directory
setwd("C:/Users/wb519501/Rep-check/RR_AFR_2026_645/files submitted/v3/Replication-Package/Training")

# Set seed for full reproducibility
set.seed(12345)

# Read the data
data <- read_dta("Prepared_4-25-2026.dta") %>%
  filter(sample10 == 1) %>%
  arrange(idstd)

# Generate 500 reshuffled versions of infc
for (i in 1:500) {
  
  new_col <- paste0("infc_", i)
  
  data[[new_col]] <- sample(
    data$infc,
    size = length(data$infc),
    replace = FALSE
  )
}

# Keep only ID and reshuffled variables
final_data <- data %>%
  select(idstd, starts_with("infc_")) %>%
  arrange(idstd)

# Export to Stata
write_dta(final_data, "resuffled_infc10.dta")

# Save session information for replication
sink("reshuffling_session_info.txt")
cat("Seed used: 12345\n\n")
sessionInfo()
sink()

# Clear memory
rm(list = ls())

# All done. You may exit R now.
